<template>
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" id="box">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <!-- 车间下拉输入框 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="车间">
              <p-select placeholder="请选择" v-model="ChangeWorkrooms"  @change="handleChangeWorkrooms">
                <p-select-option
                  :value="item.codeValue"
                  v-for="(item, index) in workrooms"
                  :key="index"
                  >{{ item.textValue }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>

          <!-- 二级工序下拉输入框 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="二级工序">
              <p-select placeholder="请选择" v-model="processTwocode" @change="handleChangeProcessTwo">
                <p-select-option
                  :value="item1.codeValue"
                  v-for="(item1, index) in processTwos"
                  :key="index"
                  >{{ item1.textValue }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>
        <!-- 工单状态 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="工单状态">
              <p-select placeholder="请选择" v-model="stateChangeValue.text"  >
                <p-select-option
                @click="stateChange(item)"
                  :value="item.text"
                  v-for="(item, index) in state"
                  :key="index"
                  >{{ item.text }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>
          <!-- 选择日期区间 -->
          <template >
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-form-item label>
                <p-range-picker v-model="time" @change="onChange" />
              </p-form-item>
            </p-col>
          </template>
           
          <!-- 搜索输入框 -->
          <!-- <template v-if="toggleSearchStatus">
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-form-item label>
                <p-input
                  placeholder="请输入"
                  v-model="queryParam.filedName"
                ></p-input>
              </p-form-item>
            </p-col>
          </template> -->

          <!-- 展开收起 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span
              style="float: left; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <p-button type="primary" @click="searchQuery" icon="search"
                >查询</p-button
              >
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
                >重置</p-button
              >
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 icon="plus"属性表示在按钮前置图标-->
    <div class="table-operator">
      <!-- 刷新按钮 -->
      <!-- <p-button @click="handleRefresh" type="primary">刷新</p-button> -->
      <!-- 下发按钮 -->
      <p-button @click="handleIssue" type="primary">下发</p-button>
      <!-- 退回按钮 -->
      <p-button @click="handleSendBack" type="primary">退回</p-button>
      <!-- 删除按钮 -->
      <!-- <p-button @click="handleDelete" type="danger">删除</p-button> -->
      <!-- 工单调整按钮 -->
      <p-button
        @click="
          () => {
            this.showModal();
          }
        "
        type="primary"
        >工单调整</p-button
      >
      <!-- 缺料上线按钮-->
      <p-button @click="handleInOnLine" type="primary">缺料上线</p-button>

      <!-- <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
          <p-button
            v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
          <p-button
            v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
      </template>-->

      <!-- 高级查询按钮-->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>

      <p-dropdown v-for="(item, index) in groupTag" :key="index">
        <p-button>
          {{ item.name }}
          <p-icon type="down" />
        </p-button>
        <p-menu slot="overlay">
          <template v-for="(items, indexs) in item.data">
            <p-menu-item
              v-if="items.optType == 'js'"
              :key="indexs"
              @click="cgButtonJsHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{ items.buttonName }}
            </p-menu-item>
            <p-menu-item
              v-else-if="items.optType == 'action'"
              :key="indexs"
              @click="cgButtonActionHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{ items.buttonName }}
            </p-menu-item>
          </template>
        </p-menu>
      </p-dropdown>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown>

    </div>

    <!-- table区域-begin -->

    <!-- 导入导出功能栏 -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <!-- <a @click="handleExportXls('工艺路线维护')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a> <p-icon type="import" />导入 </a>
          </p-upload> -->
          <p-divider type="vertical" />
          <a @click="loadData()"> <p-icon type="sync" />刷新 </a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12" :key="index">
                        <p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a> <p-icon type="setting" />自定义列 </a>
          </p-popover>
        </span>
      </div>

      <!-- 工序工单Table信息列表区域 -->
      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        
        @change="handleTableChange"
        :customRow="setHandleClick"
        :rowClassName="setRowColor"
      >
        <template slot="qistate" slot-scope="">
          <p></p>
        </template>

        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无此图片</span
          >
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>

        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无此文件</span
          >
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
            >下载</p-button
          >
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm
                  title="确定删除吗?"
                  @confirm="() => handleDelete(record.id)"
                >
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length > 0"
                v-for="(btnItem, btnIndex) in cgButtonLinkList"
              >
                <p-menu-item
                  :key="'cgbtnLink' + btnIndex"
                  v-if="showLinkButton(btnItem, record)"
                >
                  <a
                    href="javascript:void(0);"
                    @click="
                      cgButtonLinkHandler(
                        record,
                        btnItem.buttonCode,
                        btnItem.optType
                      )
                    "
                  >
                    <p-icon
                      v-if="btnItem.buttonIcon"
                      :type="btnItem.buttonIcon"
                    />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
      </p-table>
    </div>
    <!-- table区域-end -->

    <mesMfProcessRouteMaintenance-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
    ></mesMfProcessRouteMaintenance-modal>
    <Fx-compontens-modal
      @ok="modalFormOk"
      ref="modalCompon"
      :getList="queryInfo"
      :title="title"
      :dictOptions="dictOptions"
    ></Fx-compontens-modal>

    <!-- 工序工单调整对话框 -->
    <div>
      <p-modal v-model="visible" title @ok="handleOk" width="70%">
        <!-- 子组件模板标签 -->
        <MesMfProcessOrderAdjustment
          :rowInfo="rowInfo"
          @sentDataIfo="receiveInfo"
        ></MesMfProcessOrderAdjustment>
      </p-modal>
    </div>
    <!-- 手动触发缺料上线对话框 -->
    <div>
      <p-modal v-model="onlineVisible"  title="通知" width="40%">
        <template slot="footer">
          <p-button key="back" @click="handleCancelManual">取消</p-button>
          <p-button key="submit" type="primary" @click="handleManualSubmit"
            >提交</p-button
          >
        </template>
        <p style="line-height: 40px">物料不齐套，是否提交缺料上线审批？</p>
      </p-modal>
    </div>
    <!-- 工单详情对话框 -->
    <div>
      <p-modal v-model="workOrderDetailsVisible" destroyOnClose="true" width="70%" :footer="null">
        <MesMfWorkOrderDetailsTable :rowId="rowId"></MesMfWorkOrderDetailsTable>
      </p-modal>
    </div>
    <!-- 生产插单通知 -->
    <div>
      <p-modal v-model="informVisible" :confirmLoading="cdbtnLoad" okText="提交" @ok="handleSentBill" title="通知" width="40%">

        <p style="line-height: 40px">
          工序工单号{{
            this.informData[0]
          }}下发时间少于配送周期，是否触发生产插单审批？
        </p>
      </p-modal>
    </div>
    <!-- 缺料上线对话框 -->
    <div>
      <p-modal v-model="starvingOnlineVisible" :confirmLoading="qlbtnLoad" okText="提交" @ok="handleSureOnlie" title="通知" width="40%">
        <p style="line-height: 40px">
          工序工单号{{ this.informData1[0] }}物料不齐套，是否提交缺料上线审批
        </p>
      </p-modal>
    </div>
    <!-- 退回对话框 -->
    <div>
      <p-modal v-model="backVisible" title="工单退回" width="40%">
        <template slot="footer">
          <p-button key="back" @click="handleCancelBack">取消</p-button>
          <p-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleSureBack"
            >确定</p-button
          >
        </template>
        <p style="line-height: 40px">工单退回操作请确认?</p>
      </p-modal>
    </div>
    <!-- 工单下发对话框 -->
    <div>
      <p-modal v-model="orderVisible" title="提醒" width="40%">
        <template slot="footer">
          <p-button key="back" @click="handleCancelOrder">取消</p-button>
          <p-button key="submit" type="primary" @click="handleOrder"
            >确定</p-button
          >
        </template>
        <p style="line-height: 40px">下发工序工单，是否确认？</p>
      </p-modal>
    </div>
    <!-- 工单删除对话框 -->
    <div>
      <p-modal v-model="deleteVisible" title="提醒" width="40%">
        <template slot="footer">
          <p-button key="back" @click="handleCancelDelete">取消</p-button>
          <p-button key="submit" type="primary" @click="handleSureDelete"
            >确定</p-button
          >
        </template>
        <p style="line-height: 40px">
          删除已选工序工单，关联生产工单同步删除，是否确认？
        </p>
      </p-modal>
    </div>
  </p-card>
</template>
<script>
import MesMfWorkOrderDetailsTable from "@c/Privately/MesMfWorkOrderDetailsTable.vue";
import MesMfProcessOrderAdjustment from "@c/Privately/MesMfProcessOrderAdjustment.vue";
import JDictSelectTag from "@/components/SelectTagMes/JDictSelectTagMes.vue";

import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import {ajaxGetDictItems} from "@/api/api"
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
import MesMfProcessRouteMaintenanceModal from "./modules/MesMfProcessRouteMaintenanceModal";

import Vue from "vue";
import moment from "moment";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction, putAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "processType",
    text: "工单类型",
    type: "string",
  },
  {
    value: "productionno",
    text: "生产工单",
    type: "string",
  },
  {
    value: "processbillno",
    text: "工序工单",
    type: "string",
  },
  {
    value: "processTwoname",
    text: "二级工序",
    type: "string",
  },
  {
    value: "lineno",
    text: "线体",
    type: "string",
  },
  {
    value: "productcode",
    text: "产品编码",
    type: "string",
  },
  {
    value: "productname",
    text: "产品名称",
    type: "string",
  },
  {
    value: "billnoStatus",
    text: "工单状态",
    type: "string",
  },
  {
    value: "qistate",
    text: "物料齐套状态",
    type: "string",
  },
  {
    value: "starttime",
    text: "计划开始时间",
    type: "string",
  },
  {
    value: "insertStatas",
    text: "插单上线审批状态",
    type: "string",
  },
   {
    value: "completiontime",
    text: "计划完成时间",
    type: "string",
  },
  {
    value: "schedule",
    text: "完成进度",
    type: "string",
  },
  
];

export default {
  name: "MesMfProcessRouteMaintenanceList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    MesMfProcessRouteMaintenanceModal,
    // 注册JDictSelectTag组件
    JDictSelectTag,
    //工序工单调整
    MesMfProcessOrderAdjustment,
    MesMfWorkOrderDetailsTable,
  },
  data() {
    return {
      stateChangeValue:{},
      state:[],
      cdbtnLoad:false,
      qlbtnLoad:false,
      // 时间区间
      time:undefined,
      // 搜索车间
      ChangeWorkrooms:"",
      //搜索二级工序编码
      processTwocode:'',
      //工单删除对话框
      deleteVisible: false,
      //工单下发对话框
      orderVisible: false,
      //手动触发缺料上线对话框
      onlineVisible: false,
      //工单退回
      backVisible: false,
      //缺料上线
      starvingOnlineVisible: false,
      informData: [],
      informData1: [],
      //生产插单通知
      informVisible: false,
      adjustInfo: {},
      processAdjustmentParam: {
        elements: "",
      },
      //row info
      rowInfo: {},
      //saveRow.id
      rowId: "",
      rowColor: "rowColor",
      //工单详情对话框
      workOrderDetailsVisible: false,
      //获取查询条件:二级工序
      processTwos: [],
      //获取查询条件:车间
      workrooms: [],
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      isRepeat:[],//工单是否审批中
      moment,
      //控制工序工单调整对话框的显示与隐藏
      visible: false,
      superQueryParams: "",
      description: "工艺路线维护管理页面",
      cgButtonLinkList: [],
      title: "", //存表名
      EnhanceJS: "",
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "工单类型",
          align: "center",
          dataIndex: "processType",
          key: "processType",
          customRender: (text) => {
            if (text === 0) {
              return "标准工单";
            } else if (text === 1) {
              return "返修工单";
            } else if (text === 2) {
              return "拆零工单";
            } else if (text === 3) {
              return "改配工单";
            } else if (text === 4) {
              return "中试首样工单";
            } else if (text === 5) {
              return "非常规工单";
            } else if (text === 6) {
              return "中试小批量工单";
            } else if (text === 7) {
              return "工序外协工单";
            } else if (text === 8) {
              return "维修工单";
            } else if (text === 9) {
              return "科研加工工单";
            } else {
              return false;
            }
          },
        },
        {
          title: "任务来源",
          align: "center",
          dataIndex: "taskSource",
          key: "taskSource",
        },
        {
          title: "车间名称",
          align: "center",
          dataIndex: "workroomname",
          key: "workroomname",
        },
        {
          title: "车间编码",
          align: "center",
          dataIndex: "workroomno",
          key: "workroomno",
        },
        {
          title: "生产工单",
          align: "center",
          dataIndex: "productionno",
          key: "productionno",
        },
        {
          title: "工序工单",
          align: "center",
          dataIndex: "processbillno",
          key: "processbillno",
        },
        {
          title: "二级工序",
          align: "center",
          dataIndex: "processTwoname",
          key: "processTwoname",
        },
        {
          title: "线体",
          align: "center",
          dataIndex: "lineno",
          key: "lineno",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "productcode",
          key: "productcode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "productname",
          key: "productname",
        },
        {
          title: "计划数量",
          align: "center",
          dataIndex: "planQty",
          key: "planQty",
        },
        {
          title: "工单状态",
          align: "center",
          dataIndex: "billnoStatus",
          key: "billnoStatus",
          customRender: (text) => {
            if (text === -1) {
              return "已删除";
            } else if (text === 0) {
              return "未发布";
            } else if (text === 1) {
              return "已发布";
            } else if (text === 2) {
              return "已开工";
            } else if (text === 3) {
              return "已暂停";
            }
          },
        },
        {
          title: "物料齐套状态",
          align: "center",
          dataIndex: "qistate",
          key: "qistate",
          customRender: (text) => {
            if (text === 0) {
              return "未齐套";
            } else if (text === 1) {
              return "齐套";
            } else if (text === 2) {
              return "外协已确认";
            } else {
              return false;
            }
          },
        },
        {
          title: "计划开始时间",
          dataIndex: "starttime",
          key: "starttime",
          align: "center",
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: "插单上线审批状态",
          dataIndex: "insertStatas",
          key: "insertStatas",
          align: "center",
          customRender: (text) => {
            if (text === 1) {
              return "审批中";
            } else if (text === 2) {
              return "审批通过";
            }
          },
        },
        {
          title: "缺料上线审批状态",
          dataIndex: "starving",
          key: "starving",
          align: "center",
          customRender: (text) => {
            if (text === 1) {
              return "审批中";
            } else if (text === 2) {
              return "审批通过";
            }
          },
        },
        {
          title: "计划完成时间",
          dataIndex: "completiontime",
          key: "completiontime",
          align: "center",
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: "完成进度",
          dataIndex: "schedule",
          key: "schedule",
          align: "center",
          scopedSlots: {
            customRender: "schedule",
          },
        },
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      url: {
        //分页获取工序工单计划列表
        list: "/mes-manufacture/mfProcess/list",
        delete: "/mes-manufacture/auto/mesMfProcessRouteMaintenance/delete",
        //批处理删除
        deleteBatch:
          "/mes-manufacture/auto/mesMfProcessRouteMaintenance/deleteBatch",
        exportXlsUrl:
          "/mes-manufacture/auto/mesMfProcessRouteMaintenance/exportXls",
        importExcelUrl:
          "/mes-manufacture/auto/mesMfProcessRouteMaintenance/importExcel",
        getColumns: "/mes-manufacture/online/cgform/api/getColumns/",
        buttonAction: "/mes-manufacture/online/cgform/api/doButton",
        sendBackButton: "/mes-manufacture/mfProcess/back",
        adjustmentButton: "/mes-manufacture/mfProcess/adjustment",
        //获取查询条件
        conditions: "/mes-manufacture/mfProcess/getFilter",
        //工单刷新
        refresh: "/mes-manufacture/mfProcess/refresh",
        //工单下发
        down: "/mes-manufacture/mfProcess/distribute",
        //根据id删除工序工单计划
        delete: "/mes-manufacture/mfProcess/",
        //缺料上线
        inonline: "/mes-manufacture/mfProcess/lackMaterial",
        //车间
        workroom: "/mes-manufacture/mfProcess/getFilter",
        //线体
        processTwos: "/mes-manufacture/mfProcess/getFilter",
        //工单调整
        adjust: "/mes-manufacture/mfProcess/adjustment",
        //工单插班
        bill: "/mes-manufacture/mfProcess/insertOrder",
        //提示缺料上线
        online: "/mes-manufacture/mfProcess/lackMaterialWarning",
      },
      dictOptions: {},
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
  },
  created() {
    // this.initButtonList();
    this.initColumns();
    this.initCheJianData();
    this.initProcessTowsData();
    this.loadState()
  },
  mounted() {
    this.receiveInfo();
  },
  methods: {
    setRowColor(record) {
      if (record.qistate === "未齐套") {
        return "rowColor";
      }
    },
    handleCancelOnline() {
      this.starvingOnlineVisible = false;
    },
    handleCancelButton() {
      this.informVisible = false;
    },
    //缺料上线审批
    handleSureOnlie() {
        this.qlbtnLoad=true
      putAction(this.url.online, { ids: this.informData1 }).then((res) => {
        if (res.success) {
          this.$message.success("提交缺料审批成功");
          this.starvingOnlineVisible = false;
          this.qlbtnLoad=false
          this.loadData();
        }else{
          this.$message.error(res.msg)
          this.qlbtnLoad=false
        }
      });
    },

    // 选择数据日期区间
    onChange(val,data){
      this.time=val
      this.startDate=moment(data[0]).format("YYYY-MM-DD");
      this.endDate=moment(data[1]).format("YYYY-MM-DD");
    },

    //提交工单插班
    handleSentBill() {
        this.cdbtnLoad=true
      putAction(this.url.bill, { ids: this.informData }).then((res) => {
        if (res.success) {
          this.$message.success("提交生产插单审批成功");
          this.informVisible = false;
          this.cdbtnLoad=false
          this.loadData();
        }else{
          this.$message.error(res.msg)
          this.cdbtnLoad=false
        }
      });
    },
    //子传父
    receiveInfo(data) {
      this.adjustInfo = data;
    },
    //单选选择
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      this.rowInfo = selectionRows[0];
      console.log(      this.selectionRows);
    },
    //Table单击
    setHandleClick(row, index) {
      return {
        style:{
          color:row.qistate==0?"#d53333":'rgb(0, 0, 0)',
        },
        on: {
          dblclick: (ev) => {
            this.workOrderDetailsVisible = true;
            this.rowId = row.id;
          },
        },
      };
    },
    //二级工序下拉框改变事件
    handleChangeProcessTwo(value) {
      this.queryParam.processTwocode=value
      const ptwo = {
        processTwocode: value,
        limit:10,
        pageNo:1
      };
      getAction(this.url.list, ptwo).then((res) => {
        if (res.success) {
          console.log(res.data.records)
          this.dataSource = res.data.records;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
      });
    },
    searchReset(){
      this.processTwocode=''
      this.ChangeWorkrooms=""
      this.time=[]
      this.loadData()
    },
    //二级工序请求数据
    initProcessTowsData() {
      //当天开始时间
      let startDate = this.moment(new Date().getTime()).format(
        "YYYY-MM-DD 00:00:00"
      );
      //当天结束时间
      let endDate = this.moment(new Date().getTime()).format(
        "YYYY-MM-DD 23:59:59"
      );

      getAction(this.url.processTwos, { startDate, endDate }).then((res) => {
        let arrProcessTows = [];
        if (res.success) {
          //this.$message.success(res.msg);
          //将请求车间数据保存到processTwos数组里面
          res.data.processTwos.forEach((item) => {
            if (item !== null) {
              arrProcessTows.push(item);
            }
          });
          this.processTwos = arrProcessTows;
          // console.log(this.processTwos);
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },

    //车间下拉选择框改变事件
    handleChangeWorkrooms(val) {
      this.queryParam.workroomno=value
      const info = {
        workroomno: val,
         limit:10,
        pageNo:1
      };
      getAction(this.url.list, info).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
      });
    },

    //获取车间请求数据
    initCheJianData() {
      let startDate = this.moment(new Date().getTime()).format(
        "YYYY-MM-DD 00:00:00"
      );
      let endDate = this.moment(new Date().getTime()).format(
        "YYYY-MM-DD 23:59:59"
      );
      getAction(this.url.workroom, { startDate, endDate }).then((res) => {
        let chejianWorkroom = [];
        if (res.success) {
          //this.$message.success(res.msg);
          //将请求车间数据保存到workrooms数组里面
          res.data.workrooms.forEach((item) => {
            if (item !== null) {
              chejianWorkroom.push(item);
            }
          });
          this.workrooms = chejianWorkroom;
          console.log(this.workrooms);
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    //控制工序工单调整对话框显示和隐藏
    showModal() {
      this.visible = true;
    },
    //工单调整提交确认
    handleOk(e) {
      const elements = this.adjustInfo;
      console.log(elements);
      putAction(this.url.adjust, { elements: elements }).then((res) => {
        if (res.success) {
          this.$message.success("工单调整成功");
        }
      });
      this.visible = false;
    },

    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },

   stateChange(data){
     this.stateChangeValue=data
   },
    initDictConfig() {},

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    // 点击btn获取数据
    // btnGetData(tableName, title) {
    //   getAction(`${this.url.getColumns}`, {
    //     tableName: tableName,
    //   }).then((res) => {
    //     if (res.code == 0) {
    //       this.queryInfo = res.data.columns;
    //       this.title = title;
    //       this.dictOptions = res.data.dictOptions;
    //       this.showDemoModal();
    //     } else {
    //       this.$message.warning(res.msg);
    //     }
    //   });
    // },
    

    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
      console.log(dest);
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    // initButtonList() {
    //   getAction(`${this.url.getColumns}8ac49ec7733bce48017355583e54011d`).then(
    //     (res) => {
    //       console.log("--获取自定义按钮->>", res);
    //       if (res.success) {
    //         this.code = res.data.code;
    //         this.initCgButtonList(res.data.cgButtonList);
    //         this.initCgEnhanceJs(res.data.enhanceJs);
    //         this.getGroupTag(res.data.cgButtonList);
    //       } else {
    //         this.$message.warning(res.msg);
    //       }
    //     }
    //   );
    // },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },

    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      let params = this.getQueryParams(); //查询条件
      this.loading = true;
      console.log(params)
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
          
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    //刷新工单数据请求
    // handleRefresh() {
    //   //当天开始时间
    //   let startDate = this.moment(new Date().getTime()).format(
    //     "YYYY-MM-DD 00:00:00"
    //   );
    //   //当天结束时间
    //   let endDate = this.moment(new Date().getTime()).format(
    //     "YYYY-MM-DD 23:59:59"
    //   );
    //   getAction(this.url.refresh, { startDate, endDate }).then((res) => {
    //     if (res.success) {
    //       this.$message.success("刷新成功");
    //       // this.loadData();
    //     }
    //     if (res.code === 510) {
    //       this.$message.warning(res.msg);
    //     }
    //     this.loading = false;
    //   });
    // },
    getQueryParams() {
      // 获取查询条件
      const sqp = {};
     if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(
        sqp,
        this.queryParam,
        this.isorter,
        this.filters
      );
      console.log(param)
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      param.startDate = this.startDate;
      param.endDate = this.endDate;
      param.keyword=this.queryParam.filedName
      param.processTwocode=this.queryParam.processTwocode
      param.workroomno=this.queryParam.workroomno
      param.billnoStatus=this.stateChangeValue.value
      return filterObj(param);
    },

   

    //下发工单数据请求
    handleIssue() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning("请选中一条记录");
      } else {
        this.selectionRows.forEach(item=>{
          if(item.billnoStatus==1){
           this.$message.warning('该工单已下发')
            return
          }else if(item.billnoStatus==2){
            this.$message.warning('该工单已开工')
            return
          }else{
            this.orderVisible = true;
          }
        })
      
      }
    },
    handleOrder() {
      this.orderVisible = false;
      this.isRepeat=[]
      if (this.rowInfo.billnoStatus === 0) {
        this.selectionRows.forEach((item) => {
          if (item.insertStatas != 1 && item.starving != 1) {this.isRepeat.push(true)} else {this.isRepeat.push(false)}
        });
        if(this.isRepeat.indexOf(false)==-1){
          putAction(this.url.down, { ids: this.selectedRowKeys }).then(
              (res) => {
                if (res.success) {
                  this.informData = res.data.elementWorks;
                  this.informData1 = res.data.elementNoDis;

                  if (res.data.elementWorks.length) {
                    this.informVisible = true;
                  }
                  if (res.data.elementNoDis.length) {
                    this.starvingOnlineVisible = true;
                  }
                  if (
                    res.data.elementWorks.length == 0 &&
                    res.data.elementNoDis.length == 0
                  ) {
                    this.loadData();
                    this.$message.success("下发成功");
                  }
                }
                if (res.code === 510) {
                  this.$message.warning(res.msg);
                }
              }
            );
        }else{
            this.$message.warning("工单正在审批中");
        }
      } else {
        this.$message.warning("不符合工单下发要求");
        this.orderVisible = false;
      }
    },
    handleCancelOrder() {
      this.orderVisible = false;
    },
    handleCancelBack() {
      this.backVisible = false;
    },
    //工单退回请求数据
    handleSureBack() {
      if (this.rowInfo.billnoStatus !== 2 || 3)
        putAction(this.url.sendBackButton, { ids: this.selectedRowKeys }).then(
          (res) => {
            if (res.success) {
              this.$message.success("工单退回成功");
              this.loadData();
              this.backVisible = false;
            } else {
              this.$message.warning("不符合工单退回要求");
            }
          }
        );
    },
    //工单退回对话框
    handleSendBack() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning("请选中一条记录");
      } else {
        let ISstart=true
        this.selectionRows.forEach(item=>{
          if(item.billnoStatus==2){
            ISstart=false
          }
        })
        if(ISstart){
          this.backVisible = true;
        }else{
          this.$message.error('该工单已开工不可退回')
        }
        
      }
    },
    //工单删除对话框
    handleDelete() {
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      } else if (!this.selectedRowKeys.length) {
        this.$message.warning("请先选中一条记录");
        return false;
      } else {
        console.log(this.rowInfo)
        if(this.rowInfo.billnoStatus>=2){
           this.$message.error("该工单不可删除");
        }else{
            this.deleteVisible = true;
        }
        
      }
    },
    handleSureDelete() {
      if (this.rowInfo.billnoStatus !== 2) {
        const ids = this.selectedRowKeys.toString();
        deleteAction(this.url.delete + ids).then((res) => {
          if (res.success) {
            this.$message.success("删除已选工序工单成功");
            //刷新表单数据
            this.loadData();
            this.deleteVisible = false;
          }
          if (res.code === 510) {
            this.$message.warning(res.msg);
          }
          this.loading = false;
        });
      }
    },
    handleCancelDelete() {
      this.loadData();
      this.deleteVisible = false;
    },
    //工单调整数据请求
    handleAdjustment() {
      let arr = [];
      this.dataSource.forEach((item) => {
        this.selectedRowKeys.forEach((ele) => {
          if (item.id === ele) {
            const objec = {
              id: item.id,
              priority: item.priority,
            };
            arr.push(objec);
          }
        });
      });

      putAction(this.url.adjustmentButton, arr).then((res) => {
        if (res.success) {
          this.$message.success(res.msg);
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    // 手动缺料上线对话框
    handleInOnLine() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning("请选择一条记录");
      } else {
        this.onlineVisible = true;
      }
    },
    handleManualSubmit() {
      this.onlineVisible = false;
      if (
        this.rowInfo.billnoStatus === -1 ||
        (this.rowInfo.qistate === 1 &&
          this.rowInfo.starving !== 1 &&
          this.rowInfo.starving !== 2)
      ) {
        putAction(this.url.inonline, { ids: this.selectedRowKeys }).then(
          (res) => {
            if (res.success) {
              this.$message.success("缺料上线提交成功");
              this.loadData();
            }
            if (res.code === 510) {
              this.loading = false;
            }
          }
        );
      } else {
        this.$message.warning("不符合缺料上线提交条件");
        return false;
      }
    },
    loadState(){
      ajaxGetDictItems("mes_billno_status").then(res=>{
             if(res.code==0){
                 this.state=res.data
             }else{
                 this.$message.error(res.msg)
             }
         })
    },
    handleCancelManual() {
      this.onlineVisible = false;
    },
    handleTableChange(a){
      this.ipagination=a
      this.loadData()
    },

  },
};
</script>
<style scoped lang="less">
.rowColor {
  background: red;
}
</style>
